package com.outfoodmanage.utils;

/**
 * @Author huisonglin
 * @Description
 * @PackageName intelligent-vehicle-platform
 * @Package com.intelligent.utils
 * @Date 2024-01-03 17:27
 * @Version 1.0
 */
import java.util.Random;
import java.util.TreeMap;

public class WeightedRandom {
    private TreeMap<Integer, String> weightMap;
    private Random random;

    public WeightedRandom() {
        weightMap = new TreeMap<>();
        random = new Random();
    }

    public void addValue(String value, int weight) {
        int totalWeight = weightMap.isEmpty() ? 0 : weightMap.lastKey();
        weightMap.put(totalWeight + weight, value);
    }

    public String getRandomValue() {
        int totalWeight = weightMap.lastKey();
        int randomValue = random.nextInt(totalWeight + 1);

        return weightMap.ceilingEntry(randomValue).getValue();
    }

//    public static void main(String[] args) {
//        WeightedRandom weightedRandom = new WeightedRandom();
//        weightedRandom.addValue("A", 4);
//        weightedRandom.addValue("B", 2);
//        weightedRandom.addValue("C", 1);
//
//        for (int i = 0; i < 70; i++) {
//            String randomValue = weightedRandom.getRandomValue();
//            System.out.println(randomValue);
//        }
//    }
}